<script setup lang="ts">
import {onMounted, ref, watch} from 'vue';
import {useRoute} from "vue-router";
import {Loading, Refresh, Search} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {
  deleteOrder,
  cancelOrder,
  getOrderByNo,
  getOrderByStatus,
  getOrderByUserId,
  updateInvoice,
  updateAddress,
  getUserAddresses,
  updatePayTime,
  alipay
} from "@/router/api";
import {useUserStore} from "@/stores/userStore";

const route = useRoute();
const userStore = useUserStore()
const userId = route.params.id;
const suppressWatch = ref(false);
const editDialog = ref(false);
const orderDialog = ref(false);
// 展开的订单ID
const expandedOrderId = ref<number | null>(null);
// 展开/收起订单详情
const toggleOrder = (orderId: number) => {
  expandedOrderId.value = expandedOrderId.value === orderId ? null : orderId;
};
const keyword = ref('');//订单编号
const statusValue = ref('');//订单状态
const cities = [
  {value: '1', label: '待支付'},
  {value: '2', label: '已发货'},
  {value: '3', label: '已支付'},
  {value: '4', label: '已完成'},
  {value: '5', label: '已取消'},
]//类型
const tableData = ref<Array<{
  id: number;
  accept: string;
  telphone: string;
  address: string;
  def: string;
}>>([]);
const showMessage = (type: any, message: any) => {// 显示消息提示
  ElMessage({
    type,
    message,
    duration: 1000,
  });
};
const handleClear = () => {
  statusValue.value = '';
  showMessage('info', '已取消选择！');
};
onMounted(() => {
  getAllData();
  getAddress();
})
watch(statusValue, () => {
  if (suppressWatch.value) {
    suppressWatch.value = false; // 重置标志
    return;
  }
  filterData();
});
// 状态映射配置
const statusMap = {
  1: {text: '待支付', class: 'pending'},
  2: {text: '已支付', class: 'paid'},
  3: {text: '已发货', class: 'shipped'},
  4: {text: '已完成', class: 'completed'},
  5: {text: '已取消', class: 'cancelled'},
}

// 订单数据
interface Order {
  id: number;// 订单ID
  no: string;// 订单编号
  add_time: string;// 创建时间
  total_money: number;// 总金额
  address: string;// 收货地址
  accept: string;// 收货人
  telphone: string;// 联系电话
  pay_type: string;// 支付方式
  pay_time: string;// 支付时间
  finish_time: string;// 完成时间
  send_time: string;// 发货时间
  status: string;// 订单状态
  items: OrderItem[];// 订单商品
  invoice: Invoice;// 发票信息
}

//订单商品
interface OrderItem {
  id: number;// ID
  order_id: number;// 订单ID
  goods_id: number;// 关联商品ID
  name: string;// 商品名称
  image: string;// 商品图片
  price: number;// 商品价格
  num: number;// 商品数量
}

//发票信息
interface Invoice {
  id: number;// 发票ID
  order_id: number;// 订单ID
  title: string;// 发票抬头
  order_info: string;// 发票内容
  type: string;//发票类型（1:个人/2:企业）
  tax_id: string;//税号（企业发票）
  bank_card: string;//银行账户（企业发票）
  add_time: string;// 创建时间
}

// 地址数据
interface Address {
  id: number;
  accept: string;   // 收件人姓名
  telphone: string; // 联系电话
  address: string;  // 详细地址
  def: string;      // 是否默认地址 (建议改用 boolean 类型)
}

// 状态显示方法
const getStatusText = (status: string) => statusMap[status]?.text || 'Unknown'
const getStatusClass = (status: string) => statusMap[status]?.class || 'unknown'

const orders = ref<Order[]>([]);
const loading = ref(false)
const isRefreshing = ref(false);
// 模拟刷新动画
const handleRefresh = () => {
  getAllData();
  isRefreshing.value = true;
  loading.value = true;
  setTimeout(() => {
    isRefreshing.value = false;
    loading.value = false;
  }, 1000);
};
//获取所有订单
const getAllData = async () => {
  try {
    const response = await getOrderByUserId(userId);
    // 强制转换为数组，兼容 null/undefined
    const dataArray = Array.isArray(response.data) ? response.data : [];
    orders.value = dataArray.map((order: any) => ({
      ...order,
      invoice: order.invoice || null, // 处理发票可能为 null
    }));
    // 数据为空时提示
    if (dataArray.length === 0) {
      showMessage('info', '没有找到相关订单'); // 使用 info 类型提示
    }
  } catch (err) {
    showMessage('error', '获取订单失败！')
    orders.value = [];
  }
}
//按状态筛选订单
const filterData = async () => {
  if (statusValue.value === '') {
    await getAllData();
    return;
  }
  try {
    const response = await getOrderByStatus(userId, statusValue.value);
    // 强制转换为数组，兼容 null/undefined
    const dataArray = Array.isArray(response.data) ? response.data : [];
    orders.value = dataArray.map((order: any) => ({
      ...order,
      invoice: order.invoice || null, // 处理发票可能为 null
    }));
    keyword.value = '';

    // 数据为空时提示
    if (dataArray.length === 0) {
      showMessage('info', '没有找到相关订单'); // 使用 info 类型提示
    }
  } catch (error) {
    showMessage('error', '筛选失败！');
  }
}
// 搜索订单（不是模糊查询）
const searchData = async () => {
  if (keyword.value.trim() === '') {
    suppressWatch.value = true; // 禁止watch触发
    statusValue.value = '';
    await getAllData();
    return;
  }
  try {
    const response = await getOrderByNo(keyword.value);
    // 强制转换为数组，兼容 null/undefined
    const dataArray = Array.isArray(response.data) ? response.data : [];
    orders.value = dataArray.map((order: any) => ({
      ...order,
      invoice: order.invoice || null, // 处理发票可能为 null
    }));
    // 数据为空时提示
    if (dataArray.length === 0) {
      showMessage('info', '没有找到相关订单'); // 使用 info 类型提示
    }
    suppressWatch.value = true; // 禁止watch触发
    statusValue.value = '';
  } catch (error) {
    showMessage('error', '搜索失败！');
  }
}
//删除订单
const deleteOrders = (orderId: number) => {
  ElMessageBox({
    title: '删除订单',
    message: '你确定要删除该订单吗？',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    center: true,  // 中心对齐
  }).then(async () => {
    await deleteOrder(orderId);
    showMessage('success', '删除成功');
    await getAllData();
  }).catch(() => {
    showMessage('info', '已取消删除');
  });
}
//取消订单
const cancelOrders = async (orderId: number) => {
  ElMessageBox({
    title: '取消订单',
    message: '你确定要取消该订单吗？',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    center: true,  // 中心对齐
  }).then(async () => {
    await cancelOrder(orderId, '5');
    showMessage('success', '取消成功');
    await getAllData();
  }).catch(() => {
    showMessage('info', '已取消');
  });
}
//修改发票信息
const exitOrder = async (order: any) => {
  try {
    await updateInvoice({
      order_id: order.order_id,
      title: order.title,
      tax_id: order.tax_id,
      bank_card: order.bank_card,
    })
    console.log(order);
    showMessage('success', '修改成功！')
    orderDialog.value = false
  } catch (err) {
    showMessage('error', '修改失败！')
  }
}
const currentAddress = ref<Address>();
//打开修改窗口
const openEditDialog = (order: any) => {
  editDialog.value = true;
  currentAddress.value = order;
}
//获取地址信息
const getAddress = async () => {
  try {
    const res = await getUserAddresses(userId);
    tableData.value = (Array.isArray(res) ? res : []).map(item => ({
      id: item.id,
      accept: item.accept,
      telphone: item.telphone,
      address: [item.province, item.city, item.area, item.street].filter(part => part?.trim()).join('-'),
      def: item.def
    }));
  } catch (err) {
    showMessage('error', '获取地址失败！')
    tableData.value = [];
  }
}
//选择地址
const handleSelectAddress = (row: any) => {
  currentAddress.value = row;
}
//修改地址(这里是修改地址)
const exitAddress = async (order: any) => {
  try {
    await updateAddress({
      id: order.id,
      accept: currentAddress.value.accept,
      telphone: currentAddress.value.telphone,
      address: currentAddress.value.address,
    })
    order.accept = currentAddress.value.accept;
    order.telphone = currentAddress.value.telphone;
    order.address = currentAddress.value.address;
    showMessage('success', '修改成功！')
    editDialog.value = false
  } catch (err) {
    showMessage('error', '修改失败！')
  }
}
//立即支付
const payImmediately = (no: string, pay_type: string) => {
  if (userStore.userInfo.status === '0') {
    ElMessage.warning('你已被冻结，无法支付');
    return;
  }
  ElMessageBox({
    title: '支付订单',
    message: '你确定要立即支付该订单吗？',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    center: true,  // 中心对齐
  }).then(async () => {
    if (pay_type === '2') {
      const url: any = await alipay(no, '购物');
      window.location.href = url;
    }
    else {
      await updatePayTime(no);
      showMessage('success', '支付成功！');
    }
    await getAllData();
  }).catch(() => {
    showMessage('info', '已取消支付');
  });
}
</script>

<template>
  <div class="order-container">
    <h1 style="text-align: center">订单发票</h1>
    <div class="search-container">
      <el-input v-model="keyword" placeholder="请输入订单编号" clearable size="large" style="width: 250px">
        <template #prepend>
          <el-button :icon="Search" @click="searchData"/>
        </template>
      </el-input>
      <el-select v-model="statusValue" placeholder="请选择订单状态" clearable size="large"
                 @clear="handleClear"
                 style="width: 170px;margin:0 20px">
        <el-option v-for="item in cities" :key="item.value" :label="item.label"
                   :value="item.value"/>
      </el-select>
      <div class="refresh-container">
        <el-icon v-if="isRefreshing" class="loading-icon">
          <Loading/>
        </el-icon>
        <el-icon v-else class="refresh-icon">
          <Refresh @click="handleRefresh"/>
        </el-icon>
      </div>
    </div>
    <el-empty v-if="orders.length === 0" :image-size="200" description="你还没有订单"/>
    <div v-else>
      <div class="order-list" v-loading="loading">
        <div v-for="order in orders" :key="order.id" class="order-item"
             :class="{ 'is-expanded': expandedOrderId === order.id }">
          <!-- 订单头部 -->
          <div class="order-header">
            <div class="order-info" @click="toggleOrder(order.id)">
              <span class="order-id">订单编号：{{ order.no }}</span>
              <span class="order-date">创建日期：{{ order.add_time }}</span>
            </div>
            <div>
              <div class="order-status">
                <span :class="['status-badge', getStatusClass(order.status)]">{{ getStatusText(order.status) }}</span>
                <span class="order-total">总金额：￥{{ order.total_money.toFixed(2) }}</span>
              </div>
              <div style="text-align: right;margin-top: 0.5rem;">
                <el-button v-if="order.status === '1'" @click="payImmediately(order.no,order.pay_type)" size="small"
                           type="success"
                           plain>立即支付
                </el-button>
                <el-button v-if="order.status === '1'" @click="cancelOrders(order.id)" size="small" type="primary"
                           plain>取消订单
                </el-button>
                <el-button v-if="order.status === '1'" @click="deleteOrders(order.id)" size="small" type="danger" plain>
                  删除订单
                </el-button>
              </div>
            </div>
          </div>
          <!-- 下拉订单详情 -->
          <transition name="slide">
            <div v-if="expandedOrderId === order.id" class="order-details">
              <!-- 订单状态 -->
              <el-steps :active="order.status" align-center finish-status="success" process-status="finish"
                        style="width: 100%;">
                <el-step title="待支付" :description="order.add_time"/>
                <el-step title="支付时间" :description="order.pay_time"/>
                <el-step title="发货时间" :description="order.send_time"/>
                <el-step title="完成时间" :description="order.finish_time"/>
              </el-steps>
              <!-- 订单地址信息 -->
              <div>
                <div class="aa">
                  <h3>地址信息</h3>
                  <el-button v-if="order.status === '1'" @click="openEditDialog(order)" size="small" type="primary"
                             plain>修改地址
                  </el-button>
                </div>
                <el-descriptions :column="3" border>
                  <el-descriptions-item label-align="center" label="收货人" align="center">
                    {{ order.accept }}
                  </el-descriptions-item>
                  <el-descriptions-item label-align="center" label="联系电话" align="center">
                    {{ order.telphone }}
                  </el-descriptions-item>
                  <el-descriptions-item label-align="center" label="收货地址" align="center">
                    {{ order.address }}
                  </el-descriptions-item>
                </el-descriptions>
              </div>
              <!-- 订单发票信息 -->
              <div v-if="order.invoice">
                <div class="aa">
                  <h3>订单发票</h3>
                  <el-button v-if="order.status === '1'" @click="orderDialog = true;" size="small" type="primary" plain>
                    修改发票
                  </el-button>
                </div>
                <el-descriptions :column="3" border>
                  <el-descriptions-item label-align="center" label="发票抬头" align="center">
                    {{ order.invoice?.title }}
                  </el-descriptions-item>
                  <el-descriptions-item label-align="center" label="发票类型" align="center">
                    {{ order.invoice?.type === "0" ? '暂无' : order.invoice?.type === "1" ? '个人' : '企业' }}
                  </el-descriptions-item>
                  <el-descriptions-item label-align="center" label="支付方式" align="center">
                    {{ order.pay_type === "1" ? '微信支付' : order.pay_type == "2" ? '支付宝支付' : '银行卡支付' }}
                  </el-descriptions-item>
                  <el-descriptions-item label-align="center" label="税号" align="center">
                    {{ order.invoice?.tax_id || '无' }}
                  </el-descriptions-item>
                  <el-descriptions-item label-align="center" label="银行账户" align="center">
                    {{ order.invoice?.bank_card || '无' }}
                  </el-descriptions-item>
                  <el-descriptions-item label-align="center" label="创建时间" align="center">
                    {{ order.invoice?.add_time }}
                  </el-descriptions-item>
                  <el-descriptions-item label-align="center" label="发票内容" align="center">
                    {{ order.invoice?.order_info }}
                  </el-descriptions-item>
                </el-descriptions>
              </div>
              <!--  订单商品信息 -->
              <div class="section">
                <h3>商品信息</h3>
                <div class="item-list">
                  <div v-for="item in order.items" :key="item.id" class="item">
                    <img :src="item.image" alt="图片" class="item-image">
                    <div class="item-info">
                      <h4>{{ item.name }}</h4>
                      <p>数量: {{ item.num }}</p>
                      <p>单价: ￥{{ item.price.toFixed(2) }}</p>
                    </div>
                  </div>
                </div>
              </div>
              <!- 修改地址窗口 -->
              <el-dialog v-model="editDialog" title="修改订单" center draggable width="1000">
                <el-descriptions :column="3" border title="当前地址信息" style="margin-bottom: 1rem">
                  <el-descriptions-item label-align="center" label="收货人" align="center">
                    {{ currentAddress.accept }}
                  </el-descriptions-item>
                  <el-descriptions-item label-align="center" label="联系电话" align="center">
                    {{ currentAddress.telphone }}
                  </el-descriptions-item>
                  <el-descriptions-item label-align="center" label="收货地址" align="center">
                    {{ currentAddress.address }}
                  </el-descriptions-item>
                </el-descriptions>
                <!--  收货地址信息  -->
                <h3>可选地址</h3>
                <el-table :data="tableData" border highlight-current-row>
                  <el-table-column prop="accept" label="收货人" show-overflow-tooltip align="center"/>
                  <el-table-column prop="telphone" label="联系电话" show-overflow-tooltip align="center"/>
                  <el-table-column prop="address" label="收货地址" show-overflow-tooltip align="center"/>
                  <el-table-column prop="def" label="是否默认地址" show-overflow-tooltip align="center"/>
                  <el-table-column fixed="right" label="操作" show-overflow-tooltip align="center" width="100">
                    <template #default="scope">
                      <el-button size="small" @click="handleSelectAddress(scope.row)" type="primary">选择地址
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <template #footer>
                  <div>
                    <el-button @click="editDialog = false">取消</el-button>
                    <el-button type="primary" @click="exitAddress(order)">
                      修改
                    </el-button>
                  </div>
                </template>
              </el-dialog>
              <!-- 修改发票窗口 -->
              <el-dialog v-model="orderDialog" title="修改订单" center draggable width="1000">
                <el-form :model="order.invoice" status-icon scroll-to-error>
                  <el-form-item label="发票抬头" prop="title">
                    <el-input v-model="order.invoice.title" placeholder="请输入发票抬头" clearable/>
                  </el-form-item>
                  <el-form-item label="企业税号" prop="tax_id" v-if="order.invoice.type==='2'">
                    <el-input v-model="order.invoice.tax_id" placeholder="请输入企业税号" clearable/>
                  </el-form-item>
                  <el-form-item label="银行卡号" prop="bank_card" v-if="order.invoice.type === '2'">
                    <el-input v-model="order.invoice.bank_card" placeholder="请输入银行卡号" clearable/>
                  </el-form-item>
                </el-form>
                <template #footer>
                  <div>
                    <el-button @click="orderDialog = false">取消</el-button>
                    <el-button type="primary" @click="exitOrder(order.invoice)">
                      修改
                    </el-button>
                  </div>
                </template>
              </el-dialog>
            </div>
          </transition>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.search-container {
  width: 100%;
  display: flex;
  align-items: center;
  margin: 20px 0;
}

.refresh-container {
  margin-top: 4px;
  margin-left: 20px;
}

.loading-icon {
  color: #707581;
  font-size: 26px;
  animation: spin 1s infinite linear;
}

.refresh-icon {
  color: #707581;
  cursor: pointer;
  font-size: 26px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.cancelled {
  background-color: #f8d7da;
  color: #721c24;
}

.pending {
  background-color: #fff3cd;
  color: #856404;
}

.shipped {
  background-color: #cce5ff;
  color: #004085;
}

.paid {
  background-color: #d4edda;
  color: #155724;
}

.completed {
  background-color: #f3e5f5;
  color: #4a148c;
}


/*整个订单列表整体*/
.order-list {
  margin-top: 2rem;
}

.order-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.order-info {
  flex: 1;
  width: auto;
  display: flex;
  flex-direction: column;
}

.order-id {
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.order-date {
  color: #666;
  font-size: 0.9rem;
}

/*每个订单列表整体*/
.order-item {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  margin-bottom: 1rem;
  overflow: hidden;
  transition: all 0.3s ease;
}

/*订单发票头部*/
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  background-color: #f8f9fa;
  cursor: pointer;
}

/*订单状态整体*/
.order-status {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.status-badge {
  padding: 0.25rem 0.75rem;
  border-radius: 20px;
  font-size: 0.85rem;
}

.order-total {
  font-weight: 600;
  font-size: 1.1rem;
}

.order-details {
  padding: 1rem;
  background-color: white;
}

.section {
  margin-bottom: 2rem;
}

.section h3 {
  margin-bottom: 1rem;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 0.5rem;
}

.item-list {
  display: grid;
  gap: 0.4rem;
}

.item {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  padding: 0.2rem 1rem;
  border: 1px solid #eee;
  border-radius: 4px;
}

.item-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 2px;
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
}

.aa {
  display: flex;
  align-items: center;
  flex-direction: row;
  gap: 1rem;
}

.slide-enter-active, .slide-leave-active {
  transition: all 0.3s ease;
  max-height: 1000px;
}

.slide-enter-from, .slide-leave-to {
  opacity: 0;
  max-height: 0;
}
</style>